#include "junix.h"

struct A
{
	char data[1024];
	int pos;
	void (*a_read)(struct A *a, char *buf, size_t len);
	void (*a_write)(struct A *a, char *buf, size_t len);
	void (*a_print)(struct A *a);
	void (*a_init)(struct A *a);
};

void _jinit(struct A *a)
{
	memset(a->data, 0, sizeof(a->data) );
	a->pos=0;
}


void _print(struct A *a)
{
	if( a->pos ){
		if(write(STDOUT_FILENO, a->data, a->pos+1) != a->pos+1)
			err_ret("write");
	}
}

void _write(struct A *a, char *buf, size_t len)
{
	memmove( a->data+a->pos, buf, 
			len<(1024-a->pos)?len:(1024-a->pos) );
	a->pos = (a->pos+len)>1023 ? 1023: (a->pos+len) ;
}

void _read(struct A *a, char *buf, size_t len)
{
	memmove( buf, a->data, 
			len<a->pos?len:a->pos );
	a->pos = (a->pos-len)>0 ? a->pos-len: 0 ;
	if( a->pos)
		memmove(a->data+len,a->data,a->pos+1);
}

int main(int argc, char **argv)
{
	printf("size A :%d\n",sizeof(struct A) );
	struct A aa;
	aa.a_init = _jinit;
	aa.a_read = _read;
	aa.a_write = _write;
	aa.a_print = _print;

	aa.a_init(&aa);
	aa.a_write(&aa,"hello", 5);
	aa.a_print(&aa);
	printf("\n");
	aa.a_write(&aa,",world!\n", 8);
	aa.a_print(&aa);
    exit(0);
}

